//
//  ZClubPositionVC.m
//  WeClubs
//
//  Created by Zed Link on 2/5/2017.
//  Copyright © 2017 Zed. All rights reserved.
//

#import "ZClubPositionVC.h"
#import "ZPositionCell.h"
#import "ZCommentHeader.h"
#import "ZPositionChoseVC.h"
#import "ZPowerChoseVC.h"
#import "ZResourceManager.h"
#import "ZClubPostionModel.h"

#define DataSourcePositionKey @"DataSourcePersitionKey"     // 每项职位的描述字符
#define DataSourcePowerKey @"DataSourcePowerKey"        // 每项职位的所有权限数组
#define DataSourceIndexKey @"DataSourceIndexKey"        // 每项职位的所有权限对应的索引值数组

NSString * const PositionCellReuseID = @"ZPositionCellReuseID";
NSString * const PositionHeaderReuseID = @"ZClubPositionHeaderReuseID";
NSString * const PositionFooterReuseID = @"ClubZPositionFooterReuseID";

@interface ZClubPositionVC () <ZPositionChoseDelegate, ZPowerChoseDelegate, ZCommentHeaderDelegate> {
    MBProgressHUD *_hud;
    
     long _job_id;
}

/** 最后选择的职位索引 */
@property (assign, nonatomic) NSInteger lastSelectPositionIndex;
/** 最后选择的职位索引 */
@property (assign, nonatomic) NSInteger lastSelectPowerIndex;

/** 职位数据源 */
@property (strong, nonatomic) NSMutableArray *positionDataSource;
/** 每行的(职位-权限)数据源 */
@property (strong, nonatomic) NSMutableArray <NSMutableDictionary *> *powerDataSources;

@end

@implementation ZClubPositionVC

+ (instancetype)zNew
{
    return [self zNewGroup];
}

#pragma mark - About Navigation

- (void)zConfigNavigation
{
    [super zConfigNavigation];
    
    [self zAddBackItemWithGesture:YES];
    self.navigationItem.title = @"职位制定";

}


#pragma mark - View Life Cycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.tableView.contentInset = UIEdgeInsetsMake(16, 0, 0, 0);
    self.tableView.bounces = NO;
    self.tableView.estimatedRowHeight = 74;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZPositionCell" bundle:nil] forCellReuseIdentifier:PositionCellReuseID];
    [self.tableView registerClass:[ZCommentHeader class] forHeaderFooterViewReuseIdentifier:PositionHeaderReuseID];
    [self.tableView registerClass:[ZCommentHeader class] forHeaderFooterViewReuseIdentifier:PositionFooterReuseID];
    #warning done
    
    NSDictionary *dataPara = @{
                               @"user_id" : @([ZUserInfo sharedInstance].userId),
                               @"token" : [ZUserInfo sharedInstance].token,
                               @"club_id" : self.clubId,
                               @"pure_selected" :@(0)
                               };

    [HTTPRequest POST:kGet_club_jobUrl parameter:dataPara success:^(id resposeObject) {
        
        for (NSDictionary *dic in resposeObject[@"data"][@"job"]) {
        
            ZClubPostionModel * model = [[ZClubPostionModel alloc]initWithDictionary:dic];
            
            ZLog(@"_________%@---%zd--%zd",model.job_name,model.is_selected,model.job_id);
            _job_id = model.job_id;
        }
        
        
//                [resposeObject writeToFile:@"/Users/huahua/Desktop/pucker111111.plist" atomically:YES];
        
    } failure:^(NSError *error) {
        
    }];
//
//    [[ZNetManager sharedInstance] updateClubPositionListWithID:self.clubId andHasSelected:NO success:^(ZNetManagerStatus status, NSString *resultMsg, NSDictionary *data) {
//        
//    } failure:^(NSString *resultMsg, NSDictionary *data) {
//        
//    }];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.powerDataSources.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dict = self.powerDataSources[indexPath.row];
    
    ZPositionCell *cell = [tableView dequeueReusableCellWithIdentifier:PositionCellReuseID];
    [cell setIndex:indexPath.row + 1];
    [cell setPosition:dict[DataSourcePositionKey]];
    cell.powerDataSource = dict[DataSourcePowerKey];
    
    Z_WEAK_SELF
    cell.didSelectPositionChose = ^()
    {
        ZPositionChoseVC *vc = [ZPositionChoseVC zNew]; //职位制定
        vc.delegate = weakSelf;
        vc.clubId = self.clubId;
        vc.job_id = _job_id;
//        vc.positionDataSource = self.positionDataSource;
        vc.positionModels = self.positionDataSource;
        
        weakSelf.lastSelectPositionIndex = indexPath.row;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    cell.didSelectPowerChose = ^()
    {
        ZPowerChoseVC *vc = [ZPowerChoseVC zNew]; //权限选择
        vc.delegate = self;
        
        weakSelf.lastSelectPowerIndex = indexPath.row;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ZCommentHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:PositionHeaderReuseID];
    header.alignment = ZTableHeaderAlignmentCenter;
    header.style = ZTableHeaderStyleSetting;
    [header zSetTitle:@"职位制定"];
    
    return  header;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SETTING_STYLE_HEIGHT;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    ZCommentHeader *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:PositionFooterReuseID];
    footer.alignment = ZTableHeaderAlignmentFill;
    footer.style = ZTableHeaderStyleAdd;
    footer.delegate = self;
    
    NSDictionary *plusPara = @{
                           NSFontAttributeName : [UIFont systemFontOfSize:20],
                           NSForegroundColorAttributeName : HIGHTLIGHT_COLOR,
                           };
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:@"+  " attributes:plusPara];
    
    NSDictionary *titlePara = @{
                           NSFontAttributeName : [UIFont systemFontOfSize:16],
                           NSForegroundColorAttributeName : HIGHTLIGHT_COLOR,
                           };
    [attrTitle appendAttributedString:[[NSAttributedString alloc] initWithString:@"添加职位" attributes:titlePara]];
    [footer zSetAttributeTitle:attrTitle andImage:nil];
    
    return  footer;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 39;
}

#pragma mark - ZPositionChoseDelegate

- (void)positionChoseControllerdidSelectPosition:(NSString *)position
{
    // 检测列表中是否已经存在该职位
    NSDictionary *selectedDict = nil;
    for (NSDictionary *dataDict in self.powerDataSources) {
        NSString *value = [dataDict objectForKey:ClubPositionNameKey];
        if ([value isEqualToString:position]) {
            selectedDict = dataDict;
        }
    }
    
    if (selectedDict == nil)
    {
        // 新选择的职位
        NSMutableDictionary *dict = self.powerDataSources[self.lastSelectPositionIndex];
        [dict setValue:position forKey:DataSourcePositionKey];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.lastSelectPositionIndex inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        
        NSDictionary *removeDict = nil;
        for (NSDictionary *positionDict in self.positionDataSource) {
            NSString *value = [positionDict objectForKey:ClubPositionNameKey];
            if ([value isEqualToString:position]) {
                removeDict = positionDict;
            }
        }
        if (removeDict != nil) {
            [self.positionDataSource removeObject:removeDict];
        }
    }
}

#pragma mark - ZPowerChoseDelegate

- (void)powerChoseControllerDidSelectPowers:(NSArray <NSDictionary *> *)powers
{
    // 获取所有的权限名称
    NSMutableArray *powerNames = [NSMutableArray array];
    NSMutableArray *powerIndexs = [NSMutableArray array];
    [powers enumerateObjectsUsingBlock:^(NSDictionary * dict, NSUInteger idx, BOOL * _Nonnull stop) {
        [powerNames addObject:[dict objectForKey:PowerNameKey]];
        [powerIndexs addObject:[dict objectForKey:PowerIndexKey]];
    }];
    
    NSMutableDictionary *dict = self.powerDataSources[self.lastSelectPowerIndex];
    [dict setValue:powerNames forKey:DataSourcePowerKey];
    [dict setValue:powerIndexs forKey:DataSourceIndexKey];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.lastSelectPowerIndex inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

#pragma mark - ZCommentHeaderDelegate

- (void)commentHeader:(ZCommentHeader *)header didSelected:(UIButton *)sender
{
    NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
    [dataDict setValue:@"" forKey:DataSourcePositionKey];
    [dataDict setValue:[NSArray array] forKey:DataSourcePowerKey];
    [dataDict setValue:[NSArray array] forKey:DataSourceIndexKey];
    
    [self.powerDataSources addObject:dataDict];
    [self.tableView reloadData];
}

#pragma mark - Getter & Setter

- (NSMutableArray *)powerDataSources
{
    if (_powerDataSources == nil) {
        _powerDataSources = [NSMutableArray array];
        
        NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
        [dataDict setValue:@"" forKey:DataSourcePositionKey];
        [dataDict setValue:[NSArray array] forKey:DataSourcePowerKey];
        
        [_powerDataSources addObject:dataDict];
    }
    return _powerDataSources;
}

- (NSMutableArray *)positionDataSource
{
    if (_positionDataSource == nil) {
        NSMutableArray *dictArrM = [ZResourceManager sharedInstance].clubPosition;
        
        _positionDataSource = [NSMutableArray arrayWithCapacity:dictArrM.count];
        for (NSMutableDictionary *dictM in dictArrM) {
            ZMultiChoseModel *model = [[ZMultiChoseModel alloc] init];
            model.itemName = [dictM objectForKey:ClubPositionNameKey];
            model.selected = [[dictM objectForKey:ClubPositionStateKey] boolValue];
            [_positionDataSource addObject:model];
        }
    }
    return _positionDataSource;
}

@end
